﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using ZhongKeSite.Common;
using ZhongKeSite.Common.Helper;
using ZhongKeSite.Entity;
using ZhongKeSite.Service;

namespace ZhongKeSite.Web.Models
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class AuthAttribute : ActionFilterAttribute, IAuthorizationFilter
    {
        public AuthAttribute()
        {

        }

        /// <summary>
        /// 已使用到的变量参数(如不重新赋值，请勿覆盖)
        /// ViewBag.Title（标题）
        /// ViewBag.menutop_rights（头部目录菜单）
        /// ViewBag.menusecond_rights（左则目录菜单）
        /// ViewBag.table_actions（列表页的操作链接）
        /// </summary>
        /// <param name="filterContext"></param>     
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                #region 顶部底部菜单
                //菜单
                var controller = filterContext.Controller as Controller;
                IMenuService menuService = IOCContainerManager.Resolve<IMenuService>();
                var list = menuService.GetMenuList(k => k.IsAvailable == 1 && k.IsDel == 0);
                controller.ViewBag.MenuTopRight = list.Where(k => k.MenuType == MenuType.TopRight.ToString()).OrderBy(s => s.SortNo);
                controller.ViewBag.MenuTopLeft = list.Where(k => k.MenuType == MenuType.TopLeft.ToString()).OrderBy(s => s.SortNo);
                controller.ViewBag.MenuMiddleLeft = list.Where(k => k.MenuType == MenuType.MiddleLeft.ToString()).OrderBy(s => s.SortNo);
                controller.ViewBag.MenuBottom = list.Where(k => k.MenuType == MenuType.Bottom.ToString()).OrderBy(s => s.SortNo);

                string path = filterContext.HttpContext.Request.Path.Value;
                var current = list.FirstOrDefault(k => k.Link == path);
                if(current != null)
                {
                    controller.ViewBag.Title = current.Title;
                }

                //公司基本资料
                ICompanyService companyService = IOCContainerManager.Resolve<ICompanyService>();
                controller.ViewBag.CompanyInfo = companyService.GetCompany().data;
                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filterContext"></param>     
        public virtual void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            
        }

    }
}